package pers.liu.yibandemo.controller;

import cn.yiban.open.FrameUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import pers.liu.yibandemo.AppContext;
import pers.liu.yibandemo.entity.Parent;
import pers.liu.yibandemo.mapper.ParentMapper;
import pers.liu.yibandemo.service.OneTimeTokenService;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/auth")
public class AuthController {
    @Autowired
    private ParentMapper parentMapper;
    @Autowired
    private OneTimeTokenService tokenService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/login")
    public String login() throws Exception {
        String username = null;
        String userid = null;
        String acctoken = null;
//        String schoolName;
        FrameUtil util = new FrameUtil(request, response, AppContext.APP_ID, AppContext.APP_SEC, AppContext.BACK_URL);
        try {
            // 1. 从Cookie中获取token，第一次没有需要通过授权得到token
            String yiBanToken = getCookieValue(request, "token");
            System.out.println("cookie中access_token:" + yiBanToken);
            if (yiBanToken == null || yiBanToken.isEmpty()) {
                //2.(case2)再次跳转到后端,对返回的verify_request解密
                if (!util.perform()) {
                    return "go to yiban to auth";//2.(case1)进入授权，之后携带verify_request跳转实际应用地址（后端）
                }
                // 3.(case2) 授权之后携带verify_request参数再次访问本服务器，perform进行了解密，将必要信息存到Cookie
                userid = util.getUserId();
                username = util.getUserName();
                acctoken = util.getAccessToken();
                //设置到Cookie中
                setCookie(response, "username", username);
                setCookie(response, "userid", userid);
                setCookie(response, "token", acctoken);


                QueryWrapper<Parent> wrapper = new QueryWrapper<>();
                wrapper.eq("yb_user_id", userid);
                Parent one = parentMapper.selectOne(wrapper);
                if (one == null) {
//                    // 3. 请求https://openapi.yiban.cn/user/me接口获取用户信息
//                    String verifyMeResponse = restTemplate.getForObject(AppContext.UserMe_URL + "?access_token=" + acctoken, String.class);
//                    JSONObject jsonObject = JSONObject.fromObject(verifyMeResponse);
//                    JSONObject info = jsonObject.getJSONObject("info");
//                    if (info.has("yb_schoolname")) {
//                        schoolName = info.getString("yb_schoolname");
//                    }
                    Parent parent = new Parent();
                    parent.setYbUserName(username);
                    parent.setYbUserId(userid);
                    parentMapper.insert(parent);
                } else if (!Objects.equals(one.getParentName(), username)) {//同步易班更新昵称
                    Parent parent = new Parent();
                    parent.setYbUserName(username);
                    parent.setYbUserId(userid);
                    parentMapper.updateById(parent);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return "请通过易班打开！"; // 返回错误页面或其他适当的处理
        }


//        String token = tokenService.generateToken("123456");
        if (getCookieValue(request, "userid") != null && !getCookieValue(request, "userid").isEmpty()) {
            //获取cookie
            acctoken = getCookieValue(request, "token");
            userid = getCookieValue(request, "userid");
            username = getCookieValue(request, "username");
        }


        //生成一次性token
        String token = tokenService.generateToken(userid);
        System.out.println("id:" + userid + " name:" + username + " YBtoken:" + acctoken);
        System.out.println("一次性token：" + token);
        response.sendRedirect(AppContext.WEB_SITE + "?token=" + token + "&userid=" + userid);
//        response.sendRedirect(AppContext.WEB_SITE+"?token="+token+"&userid=123456");
        return "login success"; // 返回登录页面或其他适当的处理
    }

    @PostMapping("token")
    public String authToken(@RequestBody Map<String, String> map) {
        String token = map.get("token");
        String userid = map.get("userid");
        System.out.println("---------------------");
        System.out.println("验证一次性token:" + token);
        System.out.println("userid:" + userid);
        System.out.println("----------------------");
        return tokenService.verifyToken(token, userid) ? "{\"state\":true}" : "{\"state\":false}";
    }


    private String getCookieValue(HttpServletRequest request, String cookieName) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookieName.equals(cookie.getName())) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    private void setCookie(HttpServletResponse response, String cookieName, String cookieValue) {
        Cookie cookie = new Cookie(cookieName, cookieValue);
        cookie.setMaxAge(-1); // 设置为会话级Cookie
        cookie.setPath("/");  // 设置Cookie的路径
        response.addCookie(cookie);
    }

}
